﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sinacor.Infra.Common.ErrorLogging;
using PSE.Framework.ErrorLogging;
using Sinacor.Infra.Service.Security.Authorization;
using System.Net;
using System.ServiceModel;
using System.Diagnostics;
using System.Reflection;

namespace Sinacor.Infra.Service.ErrorLogging
{
    public class ServiceEnvironmentCollector : SinacorEnvironmentCollector
    {
        protected override PSE.Framework.ErrorLogging.EnvironmentData CreateEnvironmentData()
        {
            return new ServiceEnvironmentData();
        }

        protected override string GetVersion()
        {
            // Não disponível
            return "-";
        }

        public override PSE.Framework.ErrorLogging.EnvironmentData Collect(Dictionary<string, object> extensionData)
        {
            EnvironmentData environmentData = base.Collect(extensionData) as EnvironmentData;

            if (environmentData != null &&
                environmentData is ServiceEnvironmentData)
            {
                ServiceEnvironmentData serviceEnvironmentData = (ServiceEnvironmentData)environmentData;

                try
                {
                    serviceEnvironmentData.SinacorUserName = this.GetData<string>(() => AuthorizationContext.Current.LoginName, "SinacorUserName", environmentData);
                    serviceEnvironmentData.SinacorCompany = this.GetData<string>(() => AuthorizationContext.Current.CompanyId + " - " + AuthorizationContext.Current.CompanyName, "SinacorCompany", environmentData);
                    serviceEnvironmentData.SinacorModule = this.GetData<string>(() => AuthorizationContext.Current.ModuleId, "SinacorModule", environmentData);

                    serviceEnvironmentData.ServiceAddress = this.GetData<Uri>(GetServiceAddress, "ServiceAddress", environmentData);
                }
                catch (Exception ex)
                {
                    serviceEnvironmentData = (ServiceEnvironmentData)HandleException(serviceEnvironmentData, ex);
                }
            }

            return environmentData;
        }

        private Uri GetServiceAddress()
        {
            if (OperationContext.Current != null)
            {
                // Captura o endereço do serviço
                UriBuilder address = new UriBuilder(OperationContext.Current.EndpointDispatcher.EndpointAddress.Uri);
                // Troca o host do endereço pelo dns do servidor
                address.Host = Dns.GetHostEntry(Dns.GetHostName()).HostName;

                return address.Uri;
            }
            else
            {
                throw new Exception("OperationContext is not available");
            }
        }
    }
}
